#include "TetrisMap.h"

#include "Graphics.h"

#define BLOCK_SIZE 20

TetrisMap::TetrisMap(int height) : height(height)
{
	mapData = new uint16_t[height];
	for (int i = 0; i < height; i++)
	{
		mapData[i] = 0;
	}
}

void TetrisMap::move(int x, int y, int toX, int toY)
{
	destory(x, y);
	place(toX, toY);
}

void TetrisMap::destory(int x, int y)
{
	mapData[y] = mapData[y] & (~(0b1 << x));
}

bool TetrisMap::isFull(int yline)
{
	for (int i = 0; i < 16; i++)
	{
		if (!exist(i, yline)) return false;
	}
	return true;
}

void TetrisMap::clearLine(int yline)
{
	mapData[yline] = 0;
	for (int i = yline; i > 0; i--)
	{
		mapData[i] = mapData[i - 1];
	}
}

bool TetrisMap::place(int x, int y)
{
	if (x >= 16 || x < 0 || y >= height || y < 0) return false;
	mapData[y] = mapData[y] | (1 << x);
	return true;
}

bool TetrisMap::exist(int x, int y)
{
	if (x >= 16 || x < 0 || y >= height) return true;
	if (y < 0) return false;
	return (mapData[y] & (0b1 << x)) == (0b1 << x);
}

bool TetrisMap::floating(int x, int y)
{
	return !exist(x, y + 1);
}


void TetrisMap::drawMap(Graphics* graphics, TetrisMap& map, int x, int y)
{
	for (int i = 0; i < map.height; i++)
	{
		for (int j = 0; j < 16; j++)
		{
			if (map.exist(j, i))
			{
				graphics->drawRect(x + j * BLOCK_SIZE, y + i * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE, 0);
			}
			else
			{
				graphics->drawRect(x + j * BLOCK_SIZE, y + i * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE, 0xffffffff);
			}
		}
	}
}
